<template>
  <div class="team-manage-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="title-container">
        <div class="breadcrumb-title">
          <span class="main-title">队伍管理</span>
        </div>
      </div>
      <div class="button-container">
        <el-button type="primary" class="back-btn" @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>返回
        </el-button>
      </div>
    </div>

    <!-- 查询区域 -->
    <div class="query-section">
      <el-card shadow="never" class="search-card">
        <el-form :inline="true" :model="queryForm" class="search-form">
          <el-form-item label="批次" class="form-item">
            <el-select
                v-model="queryForm.batch"
                placeholder="请选择批次"
                clearable
                @change="handleBatchChange"
            >
              <el-option
                  v-for="item in batchOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="中学" class="form-item">
            <el-select
                v-model="queryForm.school"
                placeholder="请选择中学"
                clearable
                @change="handleSchoolChange"
            >
              <el-option
                  v-for="item in schoolOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="学院" class="form-item">
            <el-select
                v-model="queryForm.college"
                placeholder="请选择学院"
                clearable
                @change="handleCollegeChange"
            >
              <el-option
                  v-for="item in collegeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item class="search-input form-item">
            <el-input
                v-model="queryForm.keyword"
                placeholder="请输入队伍名称/队长姓名"
                clearable
                @clear="handleQuery"
                class="keyword-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="action-buttons">
            <el-button type="primary" @click="handleQuery" class="query-btn">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="handleReset" class="reset-btn">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
            <el-button @click="handleExport" class="export-btn">
              <el-icon><Download /></el-icon>导出数据
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 导出对话框 -->
    <el-dialog
        v-model="exportDialogVisible"
        title="正在导出表格"
        width="30%"
        :close-on-click-modal="false"
        :show-close="false"
        class="export-dialog"
    >
      <div class="export-progress">
        <el-progress
            :percentage="exportProgress"
            :stroke-width="16"
            :color="progressColor"
            :format="progressFormat"
        />
        <p class="progress-text">正在导出数据，请稍候...</p>
        <p class="estimated-time">预计剩余时间: {{ estimatedTime }}秒</p>
        <div class="dialog-footer">
          <el-button @click="cancelExport" class="cancel-btn">取消导出</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 队伍列表 -->
    <div class="team-list">
      <el-card shadow="never" class="list-card">
        <el-table
            :data="filteredTeamData"
            border
            style="width: 100%"
            row-key="id"
            class="team-table"
            :header-cell-style="headerCellStyle"
            :cell-style="cellStyle"
        >
          <!-- 表格列定义 -->
          <el-table-column prop="index" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="队伍名称" width="150" />
          <el-table-column prop="school" label="中学名称" width="150" />
          <el-table-column prop="leader" label="队长姓名" width="120" />
          <el-table-column prop="batch" label="行动批次" width="120" />
          <el-table-column prop="college" label="学院" width="150" />

          <el-table-column label="团队人数" width="150" align="center">
            <template #default="scope">
              <div class="member-count-container">
                <el-tag type="info" size="small">{{ scope.row.memberCount }}人</el-tag>
                <el-button
                    type="text"
                    size="small"
                    @click="toggleMemberDetail(scope.row)"
                    class="toggle-btn"
                >
                  {{ scope.row.showMembers ? '收起' : '详情' }}
                  <el-icon>
                    <ArrowDown v-if="!scope.row.showMembers" />
                    <ArrowUp v-else />
                  </el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="contact" label="联系方式" width="150" />
          <el-table-column prop="createTime" label="创建时间" width="180" />

          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <el-button
                  size="small"
                  @click="handleView(scope.row)"
                  class="view-btn"
              >
                <el-icon><View /></el-icon>查看
              </el-button>
              <el-dropdown trigger="click" class="more-dropdown">
                <el-button size="small" class="more-btn">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(scope.row)" class="dropdown-item">
                      <el-icon><Edit /></el-icon>编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                        @click="handleDelete(scope.row)"
                        class="dropdown-item delete-item"
                    >
                      <el-icon><Delete /></el-icon>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>

          <!-- 自定义展开行 -->
          <template #append>
            <template v-for="team in filteredTeamData" :key="team.id">
              <tr v-if="team.showMembers" class="member-detail-row">
                <td :colspan="9" class="member-detail-cell">
                  <div class="member-detail-content">
                    <div class="detail-title">团队成员详情</div>
                    <el-table
                        :data="team.members"
                        border
                        style="width: 100%"
                        class="member-table"
                    >
                      <el-table-column prop="index" label="序号" width="80" align="center" />
                      <el-table-column prop="name" label="队员姓名" width="120" />
                      <el-table-column prop="studentId" label="队员学号" width="150" />
                      <el-table-column prop="college" label="学院" width="150" />
                      <el-table-column prop="class" label="班级" width="120" />
                      <el-table-column prop="contact" label="联系方式" width="150" />
                      <el-table-column prop="joinTime" label="加入时间" width="180" />
                    </el-table>
                  </div>
                </td>
              </tr>
            </template>
          </template>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTeamData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import {
  ArrowLeft,
  ArrowDown,
  ArrowUp,
  Search,
  Refresh,
  Download,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'

const router = useRouter()

// 查询表单数据
const queryForm = reactive({
  batch: '',
  school: '',
  college: '',
  keyword: ''
})

// 下拉选项
const batchOptions = ref([
  { value: '1', label: '第一批次' },
  { value: '2', label: '第二批次' },
  { value: '3', label: '第三批次' },
  { value: '4', label: '全部批次' }
])

const schoolOptions = ref([
  { value: '1', label: '第一中学' },
  { value: '2', label: '第二中学' },
  { value: '3', label: '第三中学' },
  { value: '4', label: '全部中学' }
])

const collegeOptions = ref([
  { value: '1', label: '计算机学院' },
  { value: '2', label: '文学院' },
  { value: '3', label: '理学院' },
  { value: '4', label: '全部学院' }
])

// 模拟数据
const allTeamData = ref([
  {
    id: '1',
    index: 1,
    name: '先锋队',
    school: '第一中学',
    schoolValue: '1',
    leader: '张三',
    batch: '第一批次',
    batchValue: '1',
    college: '计算机学院',
    collegeValue: '1',
    memberCount: 5,
    contact: '13800138000',
    createTime: '2023-01-01 10:00',
    showMembers: false,
    members: [
      {
        index: 1,
        name: '张三',
        studentId: '2023001',
        college: '计算机学院',
        class: '1班',
        contact: '13800138000',
        joinTime: '2023-01-01 10:00'
      },
      {
        index: 2,
        name: '李四',
        studentId: '2023002',
        college: '文学院',
        class: '2班',
        contact: '13800138002',
        joinTime: '2023-01-12 10:00'
      },
    ]
  },
  {
    id: '2',
    index: 2,
    name: '创新队',
    school: '第二中学',
    schoolValue: '2',
    leader: '李四',
    batch: '第二批次',
    batchValue: '2',
    college: '文学院',
    collegeValue: '2',
    memberCount: 3,
    contact: '13800138001',
    createTime: '2023-01-02 11:00',
    showMembers: false,
    members: [
      {
        index: 1,
        name: '李四',
        studentId: '2023005',
        college: '商学院',
        class: '3班',
        contact: '18383903029',
        joinTime: '2023-02-17 8:00'
      },
      {
        index: 2,
        name: '王五',
        studentId: '2023008',
        college: '计算机学院',
        class: '1班',
        contact: '19980792345',
        joinTime: '2023-02-27 18:00'
      }
    ]
  },
  {
    id: '3',
    index: 3,
    name: '探索队',
    school: '第三中学',
    schoolValue: '3',
    leader: '王五',
    batch: '第三批次',
    batchValue: '3',
    college: '理学院',
    collegeValue: '3',
    memberCount: 4,
    contact: '13800138003',
    createTime: '2023-01-03 12:00',
    showMembers: false,
    members: [
      {
        index: 1,
        name: '王五',
        studentId: '2023003',
        college: '理学院',
        class: '3班',
        contact: '13800138003',
        joinTime: '2023-01-03 12:00'
      },
      {
        index: 2,
        name: '赵六',
        studentId: '2023004',
        college: '计算机学院',
        class: '2班',
        contact: '13800138004',
        joinTime: '2023-01-15 14:00'
      }
    ]
  }
])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 导出相关状态
const exportDialogVisible = ref(false)
const exportProgress = ref(0)
const estimatedTime = ref(5)
let exportInterval: number | null = null

// 计算属性：过滤后的队伍数据
const filteredTeamData = computed(() => {
  let result = [...allTeamData.value]

  // 批次筛选
  if (queryForm.batch && queryForm.batch !== '4') {
    result = result.filter(item => item.batchValue === queryForm.batch)
  }

  // 中学筛选
  if (queryForm.school && queryForm.school !== '4') {
    result = result.filter(item => item.schoolValue === queryForm.school)
  }

  // 学院筛选
  if (queryForm.college && queryForm.college !== '4') {
    result = result.filter(item => item.collegeValue === queryForm.college)
  }

  // 关键词筛选
  if (queryForm.keyword) {
    const keyword = queryForm.keyword.toLowerCase()
    result = result.filter(item => (
        item.name.toLowerCase().includes(keyword) ||
        item.leader.toLowerCase().includes(keyword)
    ))
  }

  // 更新序号
  result.forEach((item, index) => {
    item.index = index + 1
  })

  return result
})

// 表格样式
const headerCellStyle = ({ columnIndex }) => {
  return {
    backgroundColor: '#f5f7fa',
    color: '#606266',
    fontWeight: '600',
    fontSize: '14px'
  }
}

const cellStyle = () => {
  return {
    padding: '12px 0',
    fontSize: '14px'
  }
}

// 进度条颜色
const progressColor = computed(() => {
  if (exportProgress.value < 30) {
    return '#e6a23c'
  } else if (exportProgress.value < 70) {
    return '#409eff'
  } else {
    return '#67c23a'
  }
})

const progressFormat = (percentage) => {
  return `${percentage}%`
}

// 切换队员详情显示
const toggleMemberDetail = (row) => {
  // 关闭其他行的展开状态（如果需要同时只展开一行）
  allTeamData.value.forEach(item => {
    if (item.id !== row.id) {
      item.showMembers = false
    }
  })
  // 切换当前行的展开状态
  row.showMembers = !row.showMembers
}

// 查看按钮跳转到详情页
const handleView = (row) => {
  router.push({
    name: 'TeamDetail',
    params: { id: row.id }
  })
}

// 方法
const handleQuery = () => {
  currentPage.value = 1
  ElMessage.success('查询成功')
}

const handleReset = () => {
  queryForm.batch = ''
  queryForm.school = ''
  queryForm.college = ''
  queryForm.keyword = ''
  currentPage.value = 1
  ElMessage.success('重置成功')
}

// 导出数据
const handleExport = () => {
  if (filteredTeamData.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  exportDialogVisible.value = true
  exportProgress.value = 0
  estimatedTime.value = 5

  // 模拟导出进度
  exportInterval = setInterval(() => {
    exportProgress.value += 10
    estimatedTime.value = Math.max(0, estimatedTime.value - 0.5)
    if (exportProgress.value >= 100) {
      if (exportInterval) clearInterval(exportInterval)
      setTimeout(() => {
        exportDialogVisible.value = false
        ElNotification({
          title: '导出成功',
          message: '队伍数据已成功导出',
          type: 'success',
          duration: 2000
        })
      }, 500)
    }
  }, 500)
}

// 取消导出
const cancelExport = () => {
  if (exportInterval) clearInterval(exportInterval)
  exportDialogVisible.value = false
  ElMessage.warning('已取消导出')
}

const handleEdit = (row) => {
  router.push({
    name: 'TeamEdit',
    params: { id: row.id }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除队伍 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    allTeamData.value = allTeamData.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleBatchChange = () => {
  handleQuery()
}

const handleSchoolChange = () => {
  handleQuery()
}

const handleCollegeChange = () => {
  handleQuery()
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleBack = () => {
  router.go(-1)
}
</script>

<style scoped lang="scss">
.team-manage-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  gap: 16px;
}

.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  .title-container {
    .breadcrumb-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .main-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: "";
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background-color: #409EFF;
          border-radius: 2px;
        }
      }
    }
  }

  .back-btn {
    padding: 8px 15px;
    border-radius: 6px;
    transition: all 0.3s;

    &:hover {
      background-color: #ecf5ff;
      color: #409EFF;
    }

    .el-icon {
      margin-right: 5px;
    }
  }
}

.query-section {
  .search-card {
    border-radius: 8px;
    border: none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    :deep(.el-card__body) {
      padding: 16px 20px;
    }

    .search-form {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 16px;

      .form-item {
        margin-bottom: 0;
        min-width: 180px;

        :deep(.el-form-item__label) {
          font-weight: 500;
          color: #606266;
        }
      }

      .search-input {
        flex: 1;
        min-width: 240px;

        .keyword-input {
          :deep(.el-input__inner) {
            padding-left: 32px;
          }

          :deep(.el-input__prefix) {
            display: flex;
            align-items: center;
            padding-left: 8px;
          }
        }
      }

      .action-buttons {
        margin-left: auto;
        display: flex;
        gap: 12px;

        .query-btn, .reset-btn, .export-btn {
          padding: 8px 15px;
          border-radius: 6px;

          .el-icon {
            margin-right: 5px;
          }
        }

        .query-btn {
          background-color: #409EFF;
          border-color: #409EFF;

          &:hover {
            background-color: #79bbff;
            border-color: #79bbff;
          }
        }

        .reset-btn {
          color: #606266;
          border-color: #dcdfe6;

          &:hover {
            color: #409EFF;
            border-color: #c6e2ff;
            background-color: #ecf5ff;
          }
        }

        .export-btn {
          color: #409EFF;
          border-color: #c6e2ff;
          background-color: #ecf5ff;

          &:hover {
            background-color: #d9ecff;
          }
        }
      }
    }
  }
}

.export-dialog {
  border-radius: 8px;

  :deep(.el-dialog__header) {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-weight: 600;
      color: #303133;
    }
  }

  .export-progress {
    padding: 20px;
    text-align: center;

    .progress-text {
      margin: 16px 0 8px;
      color: #606266;
    }

    .estimated-time {
      margin-bottom: 20px;
      color: #909399;
      font-size: 14px;
    }

    .cancel-btn {
      padding: 8px 20px;
      border-radius: 6px;
    }
  }
}

.team-list {
  flex: 1;
  margin-bottom: 16px;

  .list-card {
    border-radius: 8px;
    border: none;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

    :deep(.el-card__body) {
      padding: 0;
    }

    .team-table {
      :deep(.el-table__header-wrapper) {
        .el-table__header {
          th {
            background-color: #f5f7fa;
          }
        }
      }

      :deep(.el-table__body-wrapper) {
        .el-table__body {
          tr:hover > td {
            background-color: #f5f7fa !important;
          }
        }
      }

      .member-count-container {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .toggle-btn {
          padding: 0 4px;
          color: #409EFF;

          .el-icon {
            margin-left: 4px;
            transition: transform 0.3s;
          }
        }
      }

      .view-btn, .more-btn {
        padding: 6px 12px;
        border-radius: 4px;

        .el-icon {
          margin-right: 4px;
        }
      }

      .view-btn {
        color: #409EFF;
        border-color: #c6e2ff;
        background-color: #ecf5ff;

        &:hover {
          background-color: #d9ecff;
        }
      }

      .more-btn {
        color: #606266;
        border-color: #dcdfe6;

        &:hover {
          color: #409EFF;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
      }

      .more-dropdown {
        margin-left: 8px;
      }

      .member-detail-row {
        background-color: #f8fafc;

        .member-detail-cell {
          padding: 0;
          border-left: none;
          border-right: none;

          .member-detail-content {
            padding: 16px;

            .detail-title {
              margin-bottom: 12px;
              font-size: 15px;
              font-weight: 600;
              color: #303133;
            }

            .member-table {
              :deep(.el-table__header-wrapper) {
                .el-table__header {
                  th {
                    background-color: #f0f2f5;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 12px 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.dropdown-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;

  .el-icon {
    margin-right: 8px;
  }
}

.delete-item {
  color: #f56c6c;

  &:hover {
    background-color: #fef0f0;
  }
}

:deep(.el-dropdown-menu__item) {
  padding: 0;
}

@media (max-width: 992px) {
  .query-section {
    .search-form {
      .form-item {
        min-width: 160px !important;
      }

      .action-buttons {
        margin-left: 0 !important;
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}

@media (max-width: 768px) {
  .top-nav {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .button-container {
      width: 100%;

      .back-btn {
        width: 100%;
      }
    }
  }

  .query-section {
    .search-form {
      .form-item {
        width: 100%;
        min-width: 100% !important;
      }

      .action-buttons {
        width: 100%;
        justify-content: space-between;
      }
    }
  }

  .export-dialog {
    width: 80% !important;
  }
}
</style>